package demo.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2020/7/14-2020
 * @Description: 这里用一句话描述这个类的作用
 */
public class AnnotationParse {
    //解析类的注解
    public static void parseTypeAnnotation() throws ClassNotFoundException {
        Class clazz=Class.forName("demo.annotation.ImoocCourse");
        //获取类上的所有注解(仅仅是类上的注解，不包括方法或者字段上的)
        Annotation[] annotations = clazz.getAnnotations();
        for (Annotation annotation: annotations) {
            CourseInfoAnnotation courseInfoAnnotation= (CourseInfoAnnotation) annotation;
            String courseName = courseInfoAnnotation.courseName();
            String courseTag = courseInfoAnnotation.courseTag();
            String courseProfile = courseInfoAnnotation.courseProfile();
            int courseIndex = courseInfoAnnotation.courseIndex();
            System.out.println("课程名称："+courseName+"课程标签:"+courseTag+"课程简介"+courseProfile+"课程序号："+courseIndex);
        }
    }

    //解析字段上的注解
    public static  void parseFileAnnotation() throws ClassNotFoundException {
        Class clazz = Class.forName("demo.annotation.ImoocCourse");
        //获取类上的所有字段，包括私有类型的，但是不包括继承过来的
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            boolean annotationPresent = field.isAnnotationPresent(PersonInfoAnnotation.class);
            if(annotationPresent){
                PersonInfoAnnotation personInfoAnnotation = field.getAnnotation(PersonInfoAnnotation.class);
                String name = personInfoAnnotation.name();
                String gender = personInfoAnnotation.gender();
                String[] language = personInfoAnnotation.language();
                System.out.println("作者的名字是:"+name+",作者的性别是："+gender+",作者一共会:"+language.length+"门语言！！！！");
            }
        }
    }

    //解析方法上的注解
    public static  void parseMethodAnnotation() throws ClassNotFoundException {
        Class clazz = Class.forName("demo.annotation.ImoocCourse");
        Method[] methods = clazz.getMethods();
        for (Method method :
                methods) {
            boolean annotationPresent = method.isAnnotationPresent(CourseInfoAnnotation.class);
            if(annotationPresent){
                CourseInfoAnnotation courseInfoAnnotation = method.getAnnotation(CourseInfoAnnotation.class);
                String courseName = courseInfoAnnotation.courseName();
                String courseTag = courseInfoAnnotation.courseTag();
                String courseProfile = courseInfoAnnotation.courseProfile();
                int courseIndex = courseInfoAnnotation.courseIndex();
                System.out.println("课程名称是："+courseName+"课程标签是："+courseTag+"课程简介是："+courseProfile+"课程序号是："+courseIndex);
            }
        }
    }
}
